package com.quartz.demo2;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
public class CronDemo2 {
	static SchedulerFactory schedFact = new StdSchedulerFactory();
	//得到默认的调度器
	volatile static Scheduler sched;

	static {
		try {
			sched = schedFact.getScheduler();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws SchedulerException {


		sched.start();

		//获取状态
		Thread t1 = new Thread(() -> getJobs(sched));
		t1.setDaemon(true);
		t1.start();


		JobDetail job = newJob(MyCronJob.class)
				.withIdentity("myCronJob", "group2") // name "myJob", group "group1"
				.build();

		LocalDateTime localDateTime = LocalDateTime.now().plusSeconds(5);
		Date date = localDateTime2Date(localDateTime);
		Trigger  trigger = newTrigger()
				.withIdentity("trigger3", "group2")
				//秒，分，时，日，月，周，年
				.withSchedule(cronSchedule("0/2 * * * * ?"))
				.forJob("myCronJob", "group2")
				.startAt(date)
				.build();
		System.out.println("定时器开始:"+LocalDateTime.now());
		sched.scheduleJob(job, trigger);



		JobDetail job1 = newJob(MyCronJob.class)
				.withIdentity("myCronJob", "group4") // name "myJob", group "group1"
				.build();
		LocalDateTime localDateTime1 = LocalDateTime.now().plusSeconds(5);
		Date date1 = localDateTime2Date(localDateTime1);
		Trigger  trigger1 = newTrigger()
				.withIdentity("trigger4", "group3")
				//秒，分，时，日，月，周，年
				.withSchedule(cronSchedule("0/3 * * * * ? 2011"))
				.forJob("myCronJob", "group4")
				.startAt(date1)
				.build();
		sched.scheduleJob(job1, trigger1);

	}

	private static String getTriggerStatusOfJob(String jobKey,String jobGroup,Scheduler scheduler) throws SchedulerException {
		if(jobGroup == null || "".equals(jobGroup)){
			//jobGroup = ;
		}
		JobKey myJobKey = JobKey.jobKey(jobKey,jobGroup);
		List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(myJobKey);
		if(!CollectionUtils.isEmpty(triggers)){
			TriggerKey key = triggers.get(0).getKey();
			Trigger.TriggerState triggerState = scheduler.getTriggerState(key);
			return triggerState.toString();
		}
		return "";
	}

	private static void getJobs(Scheduler scheduler) {
		try {
//			Thread.sleep(5000);
//			String myCronJob = getTriggerStatusOfJob("myCronJob", scheduler);
//			System.out.println(myCronJob);

			while(true){
				for (String groupName : scheduler.getJobGroupNames()) {
					for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
						String jobName = jobKey.getName();
						String jobGroup = jobKey.getGroup();
						//get job's trigger
						List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
						Date nextFireTime = triggers.get(0).getNextFireTime();
						TriggerKey key = triggers.get(0).getKey();
						Trigger.TriggerState triggerState = scheduler.getTriggerState(key);

						System.out.println("[jobName] : " + jobName + " [groupName] : "
								+ jobGroup + " - " + nextFireTime+" now state:"+ triggerState);
					}
				}
//
//				TriggerKey triggerKey = TriggerKey.triggerKey("trigger4", "group3");
//
//				Trigger.TriggerState triggerState = scheduler.getTriggerState(triggerKey);
//				System.out.println(triggerState);
				Thread.sleep(3000);
			}

		} catch (SchedulerException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	public static Date localDateTime2Date(LocalDateTime localDateTime){
		ZoneId zoneId = ZoneId.systemDefault();
		ZonedDateTime zdt = localDateTime.atZone(zoneId);//Combines this date-time with a time-zone to create a  ZonedDateTime.
		Date date = Date.from(zdt.toInstant());
		System.out.println(date.toString());//Tue Mar 27 14:17:17 CST 2018
		return date;
	}
}
